<?php
	class Auth extends CI_Controller{
		
		public function __construct(){
			parent::__construct();
			$this->load->model('users_model');
			$this->load->model('group_model');
			$this->load->model('assign_model');
			$this->load->model('module_model');
			$this->load->library('session');
		}
		
		public function index(){
			$this->load->library('session');
			if($this->session->userdata('logged_in')){
				redirect('home', 'refresh');
			}
			else{
				$this->load->helper("form");
				$this->load->library('form_validation');
				$this->form_validation->set_rules('username', 'Username', 'required');
				$this->form_validation->set_rules('password', 'Password', 'required');

				$data['title'] = "Login Panel";			
				$this->load->view('templates/header', $data);
				$this->load->view('users/login', $data);
				$this->load->view('templates/footer');
			}
		}
		
		public function login(){
			$this->load->library('form_validation');
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			
			if($this->form_validation->run() == FALSE){
				$data['title'] = "Login Panel";			
				$this->load->view('templates/header', $data);
				$this->load->view('users/login');
				$this->load->view('templates/footer');
			}
			else{
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				$result = $this->users_model->login($username, $password);
				if($result){
					$set_arr = array();
					$gid = 0;				
					foreach($result as $row){					
						// check Group ID
						$permission_data = array();
						if( $row->gid !=1 ){
							$role_arr 				= $this->assign_model->getAssign($row->gid);
							if(count($role_arr)>0)
								$permission_data 	= $this->module_model->getModuleForLogin($role_arr['module_id']);
						}
					
						$set_arr = array('id'=>$row->id,
							'username'=>$row->username,
							'password'=>$row->password,
							'gid'=>$row->gid,
							'role'=>$permission_data
						);
						$gid = $row->gid;
					}
					$this->session->set_userdata('logged_in', $set_arr);
					redirect('home', 'refresh');					
				}
				else redirect('', 'refresh');
			}
		}
		
		public function logout(){
			$this->load->library('session');
			if($this->session->userdata('logged_in')){
				$this->session->unset_userdata('logged_in');
				redirect("", "refresh");
			}
		}
	}
?>